// 包含n个action creator
// 异步action和同步action
import {AUTH_SUCCESS, ERROR_MSG, RECEIVE_USER, RESET_USER} from './action-types'

import {reqRegister,reqLogin,reqUpdateUser, reqUser} from '../api'

// 授权成功的同步action
const authSuccess = (user) => ({type:AUTH_SUCCESS, data:user});
// 错误提示信息的action
const errorMsg = (msg) => ({type: ERROR_MSG, data:msg});
// 接收用户的同步action
const receiveMsg = (user) => ({type: RECEIVE_USER, data:user});
// 重置用户的同步action
export const resetMsg = (user) => ({type:RESET_USER, data:user});
// 注册异步action
export const register = (user) => {
    const {username, password, password2, type} = user;
    // 表单前台验证
    if(password !== password2){
        return errorMsg('两次密码不一致')
    }
    if(!username){
        return errorMsg('账号不能为空')
    }
    // 表单数据合法 返回一个发ajax请求的异步函数
    return async dispatch => {
        // 发送注册的异步请求
        const response = await reqRegister({username, password, type});
        const result = response.data;
        if(result.code === 0){
            // 分发成功的action
            dispatch(authSuccess(result.data))
        }else{
            // 分发错误的action
            dispatch(errorMsg(result.msg))
        }
    }
};

export const login = (user) => {
    const {username, password} = user;
    // 表单前台验证
    if(!password){
        return errorMsg('密码不能为空')
    }
    if(!username){
        return errorMsg('账号不能为空')
    }
    return async dispatch => {
        // 发送登录的异步请求
        const response = await reqLogin(user);
        const result = response.data;
        if(result.code === 0){
            dispatch(authSuccess(result.data))
        }else{
            dispatch(errorMsg(result.msg))
        }
    }
};

export const update = (user) => {
    return async dispatch => {
        const response = await reqUpdateUser(user);
        const result = response.data;
        if(result.code === 0){      // 更新成功
            dispatch(receiveMsg(result.data))
        }else{
            dispatch(resetMsg(result.data))
        }
    }
};

// 获取用户异步action
export const getUser = () => {
    return async dispatch => {
        const response = await reqUser();
        const result = response.data;
        if(result.code === 0) {
            dispatch(receiveMsg(result.data))
        } else {
            dispatch(resetMsg(result.data))
        }
    }
};
